﻿using System;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using Whoever.Framework.Enum;
using Whoever.Framework.CustomException;
using EditorialProyectos.Business;
using EditorialProyectos.Website.Infrastructure;
using Whoever.Patterns.MVC.Filters;

namespace EditorialProyectos.Website.Controllers
{
    public class BaseController : Controller
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (SessionState.LoggedInUser != null)
            {
                var authorizationValidation =
                    Convert.ToBoolean(ConfigurationManager.AppSettings["AuthorizationValidation"]);

                if (authorizationValidation)
                {
                    if (
                        !ManagerFactory.ActionPermissionManager.HasPermission(filterContext.Controller.GetType().Name,
                            filterContext.ActionDescriptor.ActionName, SessionState.LoggedInUser))
                    {
                        if (
                            filterContext.ActionDescriptor.GetCustomAttributes(typeof (AJAXExceptionHandler), true)
                                .Count() > 0)
                        {
                            // meter este texto en el archivo de recursos.
                            throw new BusinessException("Usted no tiene permisos para acceder a esta acción.",
                                MessageType.Error);
                        }
                        else
                        {
                            filterContext.Result = new RedirectResult(Url.Action("NotAuthorized", "Security"));
                        }
                    }
                }
            }
            else
            {
                filterContext.Result = new RedirectResult(Url.Action("Main", "Account"));
            }

            base.OnAuthorization(filterContext);
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var authorizationValidation = Convert.ToBoolean(ConfigurationManager.AppSettings["AuthorizationValidation"]);

            if (authorizationValidation)
            {
                var permission = ManagerFactory.ActionPermissionManager.GetPermissions(filterContext.Controller.GetType().Name, SessionState.LoggedInUser);

                ViewBag.Permissions = permission;
            }

            base.OnActionExecuting(filterContext);
        }
    }
}
